package basic.flow 
{
	import flash.events.EventDispatcher;
	/**
	 * ...
	 * @author ...
	 */
	[Event(name = "flowComplete", type = "basic.flow.FlowFactoryEvent")]
	[Event(name = "flowItemError", type = "basic.flow.FlowFactoryEvent")]
	[Event(name = "flowItemSuccess", type = "basic.flow.FlowFactoryEvent")]
	
	public class FlowFactory extends EventDispatcher 
	{
		//内部流程数据库
		private var m_flow:Vector.<Flow>;
		private var m_complete:Vector.<Flow>;
		//系统是否在运行
		private var m_isrun:Boolean = false;
		
		public var currentFlow:Flow;
		public function FlowFactory() 
		{
			m_flow = new Vector.<Flow>();
			m_complete = new Vector.<Flow>();
		}
		
		/**
		 * 启动流程
		 */
		public function start():void {
			m_isrun = true;
			nextFlow();
		}
		
		/**
		 * 添加流程
		 * @param	flowx	需要添加的流程
		 */
		public function push(flowx:Flow):void {
			m_flow.push(flowx);
		}
		
		/**
		 * 成功事件
		 * @param	event	事件
		 */
		private function onsuccess(event:FlowEvent):void {
			currentFlow = event.target as Flow;
			this.dispatchEvent(new FlowFactoryEvent(FlowFactoryEvent.FLOW_ITEM_SUCCESS));
			if (m_flow.length == 0) {
				this.dispatchEvent(new FlowFactoryEvent(FlowFactoryEvent.FLOW_COMPLETE));
			}
		}
		
		/**
		 * 失败时候调用
		 * @param	event	失败事件
		 */
		private function onfault(event:FlowEvent):void {
			this.dispatchEvent(new FlowFactoryEvent(FlowFactoryEvent.FLOW_ITEM_ERROR));
		}
		
		/**
		 * 下一个流程
		 */
		public function nextFlow():void {
			if (!m_isrun) {return;}
			if (m_flow.length == 0) { m_isrun = false; return; }
			var flowx:Flow = m_flow.shift();
			flowx.addEventListener(FlowEvent.SUCCESS, onsuccess);
			flowx.addEventListener(FlowEvent.FAULT, onfault);
			flowx.exec();
		}
	}

}